<template>
    <div class="plan_container">
        <ZwSearchForm row-num="3" :option="searchOption" @search="search" @reset="reset" />
        <ZwTable
            ref="tableRef"
            class="table-box"
            tab-h="initial"
            :option="tableOption"
            :fetch-params="state.searchParams"
            :param-prop="state.paramProp"
            :fetch-api="fetchApi()">
            <template #headerOperate>
                <el-button @click="highSet">高级设置</el-button>
                <el-button type="primary" @click="creatPlan('create')">创建营销规则</el-button>
            </template>
        </ZwTable>
    </div>
    <ZWadvancedSetup ref="advanced" :type="6" />
</template>

<script lang="tsx">
import { defineComponent } from 'vue';
// 定义name专用script标签
// eslint-disable-next-line vue/component-definition-name-casing
export default defineComponent({ name: 'MARKETING_PLAN' });
</script>

<script setup lang="tsx">
import { ref, reactive, computed, nextTick, onActivated } from 'vue';
import { useRouter } from 'vue-router';
import ZwSearchForm from '@/components/zw/search-form/SearchForm';
import ZwTable from '@/components/zw/table/Table';
import ZWadvancedSetup from '@/components/ZWadvancedSetup.vue';
import { ElTooltip, ElButton, ElDropdown, ElDropdownMenu, ElDropdownItem, ElMessage, ElPopover } from 'element-plus';
import { deepCopy } from '@/utils/helper';
import { getCreateList } from '@/api/common';
import { ruleList, delRule, enable } from '@/api/smartMarketing/precision';

const router = useRouter();
const tableRef = ref();
const advanced: any = ref(null);
const requestFlag = ref<boolean>(false);
const currentParams = ref<any>(null);
const defaultParams = reactive({
    title: '',
    created_uid: '',
    status: '',
    period_time: [],
    created_time: []
});
const state = reactive({
    searchParams: deepCopy(defaultParams),
    paramProp: { page: '', pageSize: 'page_size' }
});
const searchOption = computed(() => {
    return [
        {
            label: '规则名称',
            name: 'title',
            value: '',
            type: 'input',
            placeholder: '请输入规则名称'
        },
        {
            label: '创建人',
            name: 'created_uid',
            value: [],
            multiple: true,
            type: 'select',
            filterable: true,
            placeholder: '请选择创建人',
            fetchOptionApi: () => {
                return new Promise(resolve => {
                    getCreateList({}).then((res: any) => {
                        const targetArr = res.map((item: any) => {
                            item.name = `${item.name}  (${item.phone})`;
                            return item;
                        });
                        resolve(targetArr);
                    });
                });
            },
            formatOption: (v: any) => ({
                label: v.name,
                value: v.id
            })
        },
        {
            label: '状态',
            name: 'status',
            value: '',
            type: 'select',
            placeholder: '请选状态',
            fetchOptionApi: () => {
                return new Promise(resolve => {
                    resolve([
                        {
                            name: '全部',
                            id: 0
                        },
                        {
                            name: '已开启',
                            id: 1
                        },
                        {
                            name: '未开启',
                            id: 2
                        }
                    ]);
                });
            },
            formatOption: (v: any) => ({
                label: v.name,
                value: v.id
            })
        },
        {
            label: '有效期',
            name: 'period_time',
            value: [],
            type: 'datePicker',
            datePickerType: 'daterange',
            datePickerFormat: 'YYYY-MM-DD HH:mm:ss',
            valueFormat: 'YYYY-MM-DD HH:mm:ss',
            startPlaceholder: '开始时间',
            endPlaceholder: '结束时间'
        },
        {
            label: '创建时间',
            name: 'created_time',
            value: [],
            type: 'datePicker',
            datePickerType: 'daterange',
            datePickerFormat: 'YYYY-MM-DD HH:mm:ss',
            valueFormat: 'YYYY-MM-DD HH:mm:ss',
            startPlaceholder: '开始时间',
            endPlaceholder: '结束时间'
        }
    ];
});

const tableOption = [
    {
        prop: 'title',
        label: '规则名称',
        minWidth: 240
    },
    {
        label: '规则设定',
        minWidth: 320,
        render({ row }: any) {
            const slotReference = () => (
                <p class="dose" vShow={row.trigger_condition_name.length > 25}>
                    {row.trigger_condition_name}
                </p>
            );
            const slotDefault = () => <p>{row.trigger_condition_name}</p>;
            return (
                <div>
                    <ElPopover
                        width={300}
                        trigger="hover"
                        vSlots={{ reference: slotReference, default: slotDefault }}></ElPopover>
                    <span vShow={row.trigger_condition_name.length <= 25}>{row.trigger_condition_name || '--'}</span>
                </div>
            );
        }
    },
    {
        label: '状态',
        width: 140,
        render({ row }: any) {
            // { ? <span style="color:#60B900">已开启</span> : '未开启'}
            // <ElSwitch vModel={row.status} active-value={1} inactive-value={2} />
            return (
                <div class="status">
                    <p vShow={row.status == 1} style="color:#60B900">
                        已开启
                    </p>
                    <p vShow={row.status == 2 || row.status == 3}>未开启</p>
                    <ElTooltip class="box-item" effect="light" content="已过期" placement="top-start">
                        <img vShow={row.status == 3} class="icon" src={'/static/ask_icon.png'} alt="" />
                    </ElTooltip>
                </div>
            );
        }
    },
    {
        label: '有效期',
        width: 140,
        render({ row }: any) {
            return <div>{row.period_type_name}</div>;
        }
    },
    {
        label: '创建人',
        width: 140,
        render({ row }: any) {
            return <div>{row.created_name || '--'}</div>;
        }
    },
    {
        label: '创建时间',
        width: 200,
        render({ row }: any) {
            return <div>{row.created_at}</div>;
        }
    },
    {
        prop: 'operate',
        label: '操作',
        fixed: 'right',
        width: 300,
        isOperate: true,
        renderOperate({ row }: any) {
            const slotDropdown = () => (
                <ElDropdownMenu>
                    <ElDropdownItem command={1} vShow={![1, 3].includes(row.status)}>
                        编辑
                    </ElDropdownItem>
                    <ElDropdownItem command={2}>删除</ElDropdownItem>
                    <ElDropdownItem command={5}>复制</ElDropdownItem>
                </ElDropdownMenu>
            );
            return (
                <>
                    <ElButton size="small" vShow={row.status == 2} onClick={() => handleCommand(3, row)}>
                        开启
                    </ElButton>
                    <ElButton size="small" vShow={row.status == 1} onClick={() => handleCommand(4, row)}>
                        关闭
                    </ElButton>
                    <ElButton size="small" onClick={() => creatPlan('look', row.id)}>
                        查看
                    </ElButton>
                    <ElButton size="small" onClick={() => handleCommand(6, row)}>
                        统计
                    </ElButton>
                    <ElDropdown size="small" vSlots={{ dropdown: slotDropdown }} onCommand={v => handleCommand(v, row)}>
                        <ElButton size="small">
                            更多
                            <el-icon class="el-icon--right">
                                <arrow-down />
                            </el-icon>
                        </ElButton>
                    </ElDropdown>
                </>
            );
        }
    }
];
const getTableH = () => {
    nextTick(() => {
        tableRef.value.getTableH();
    });
};
const fetchApi = () => {
    getTableH();
    return ruleList;
};
const search = (data: any) => {
    currentParams.value = data;
    state.searchParams = deepCopy(data);
};
const reset = (v?: any) => {
    state.searchParams = deepCopy(defaultParams);
    currentParams.value = null;
};

// 创建营销规则
const creatPlan = (type: string, id?: string | number) => {
    router.push(
        // '/smartMarketing/precisionMarketing/plan/create?type=' + type + '&id=' + id + '&copy=' + '复制营销规则'
        `/smartMarketing/precisionMarketing/plan/create?type=${type}&id=${id ? id : ''}&copy=复制营销规则`
    );
};
const fun = (data: any) => {
    enable(data).then(() => {
        ElMessage.success('操作成功');
        search(state.searchParams);
    });
};
// 更多操作按钮
const handleCommand = (command: string | number | object, row: any) => {
    switch (command) {
        case 1:
            router.push(
                '/smartMarketing/precisionMarketing/plan/create?type=' +
                    'edit' +
                    '&id=' +
                    row.id +
                    '&copy=' +
                    '复制营销规则'
            );
            break;
        case 2:
            delRule({ id: row.id }).then((res: any) => {
                ElMessage.success('删除成功！');
                search(state.searchParams);
            });
            break;
        case 3:
            fun({ id: row.id, status: 1 });
            break;
        case 4:
            fun({ id: row.id, status: 2 });
            break;
        case 5:
            router.push(
                '/smartMarketing/precisionMarketing/plan/create?type=' +
                    'copy' +
                    '&id=' +
                    row.id +
                    '&copy=' +
                    '复制营销规则'
            );
            break;
        case 6:
            router.push('/smartMarketing/precisionMarketing/plan/stat?id=' + row.id);
            break;
    }
};
// 高级设置
const highSet = () => {
    advanced.value.isShow = true;
};
onActivated((val: any) => {
    state.searchParams = { ...deepCopy(defaultParams), ...currentParams.value };
});
</script>

<style scoped lang="scss">
.plan_container {
    height: calc(100vh - 142px);
    padding: 24px;
    border: 1px solid #eaeaea;
    border-radius: 4px;
    box-sizing: border-box;
    background-color: #fff;
    display: flex;
    flex-direction: column;
    overflow: hidden;

    .zw-table {
        display: flex;
        flex-direction: column;
        flex: 1;
        overflow: hidden;

        :deep(.el-table) {
            flex: 1;

            .el-table__empty-block {
                position: absolute;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
            }
        }

        :deep(.dose) {
            text-overflow: ellipsis;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            overflow: hidden;

            /*! autoprefixer: off */
            -webkit-box-orient: vertical;
        }

        :deep(.status) {
            display: flex;
            align-items: center;

            .icon {
                width: 16px;
                height: 16px;
                margin-left: 4px;
            }
        }
    }
}
</style>
